import React from 'react';
import * as asyncLoad from '../util/asyncLoad';
import { workflowPublicFiles } from '../constants/fileConfig';
import * as _ from '../util/public/common';
import allStore from '../stores';
import { toJS, observable } from 'mobx'
import { observer, inject } from "mobx-react/index";
import Loading from './Loading';
import { getEcCom, getAntd, getLabel } from '../util/convert';
import $ from 'jquery';
import './../style/form.less';

@observer
export default class CusSignInput extends React.Component {


    
    constructor(props) {
        super(props);
        this.state = { hasLoad: false};
    }

    componentDidMount() {
        const init = () => {
            this.setState({ hasLoad: true });
        }
        asyncLoad.asyncLoadModule('workflowPublic', workflowPublicFiles, init);

        window.showInput6 = hasLoad => {
            this.setState({ hasLoad});
        }
    }

    componentDidUpdate() {
        
    }
   /* shouldComponentUpdate(nextProps, nextState) {
       return  this.props.remark !== nextProps.remark;
    }*/

    contentUtil = (str) => {
        let hea = str.substr(0, str.indexOf("<div _quotoContent='true'"));
        str = str.substr(str.indexOf("<div _quotoContent='true'"));
        str = str.replace(/<img.*?>/g, '[图片]')
        str = str.replace(/<[^>]*>|<\/[^>]*>/gm, "")
        str = str.replace(/\r|\n|\\s/gm, "");
        str = `<div class='remark-quote'>${str}</div>`;
        str = hea + str + "</div>";
        return str;
    }

    // 点击删除一个签字意见
    deleteItem(key, event) {
        const { variableMap } = allStore.globalStore;
        const remark_list = variableMap.get("remark_list");
        remark_list.delete(key);
    }

    //渲染引用签字意见列表
    getRemarkDom = (isInForm) => {
        const { Icon } = getAntd();
        const { variableMap } = allStore.globalStore;
        const remarkMap = variableMap.get("remark_list") || (observable.map ? observable.map({}) : asMap({}));
        let arr = [];
        remarkMap.forEach((value, key, map) => {
            const item = <div className='remark_list_dom' style={{ position: "relative", marginLeft: isInForm ? "10px" : "0" }}>
                <div style={{ width: isInForm ? this.state.width + "px" : "100%" }} dangerouslySetInnerHTML={{ __html: this.contentUtil(value) }}></div>
                <Icon type="cross " title="删除" style={{ position: "absolute", right: "10px", top: "10px", cursor: "pointer", color: "#333" }} onClick={this.deleteItem.bind(this, key)} />
            </div>
            if (toJS(value) !== '') {
                arr.push(item)
            }
        })

        return arr;
    }
    render() {
        const { WeaPopoverHrm } = getEcCom();
        const { hasLoad } = this.state;
        const {remark="",logid}=this.props;
        const { commonParam, markInfo = {}, variableMap, controlVariableMap, loadMarkInfo} = allStore.globalStore;
        if(variableMap.get("islsx6")!==2||window.lsxlogid!==logid){
            return <div></div>;
        }

        if (hasLoad) {
            const { WfSignInput } = window.weaWorkflowPublic;
            const { containSignInput = false,propFileCfg } = allStore.layoutStore;
            const { onChangeEvent, isInForm = false,maxHeight=0} = this.props;
            const isEditorFocus = variableMap.get('isEditorFocus');
            const remark_list = variableMap.get("remark_list");
            const { requestid, requestType, intervenorright } = commonParam;
            let { remarkInfo = {}, isHideInput, isSignMustInput, tempbeagenter, fileuserid, tempbeagentername } = markInfo;
            const isBeagent = false;
            let remarkInfo_new = {...remarkInfo,remark:remark};
            const agent = (
                <span style={{ lineHeight: "36px", paddingLeft: "10px" }}>
                    {getLabel(388045, "您当前正在代理")}
                    <WeaPopoverHrm />
                    <a href={`javaScript:openhrm(${tempbeagenter});`} onClick={e => window.pointerXY(e)} title={tempbeagentername}><span style={{ color: "#4D7AD8", cursor: "pointer" }}>{tempbeagentername}</span></a>
                    {getLabel(84398, "进行操作")}
                </span>
            )
            let isopen = true;
            return (
            
                <div   id="remark_div" style={{'color':'#000'}}>
                    {/* <div className='wf-req-sign-input' style={{
                                background: !(isopen) ? "#ffffff" : "#ffffff",
                                border: (isopen) && "1px solid #E2E2E2",
                                borderLeft: isopen ? "1px solid #E2E2E2" : isSignMustInput == '1' && "2px solid #FF4949",
                                cursor: !isopen ? "default" : "default",
                                paddingLeft:"10px"
                            }}>
                        <i className="icon-coms-Need-feedback" style={{ marginRight: "10px", fontSize: "15px", color: "#AFAFAF ", lineHeight: "40px", display: "inline-block", verticalAlign: "bottom" }} />
                        <span style={{ color: "#A0A0A0" }}>{getLabel(17614, '签字意见')}</span>
                        {(isSignMustInput == '1' && isopen) && <span style={{ color: "red", marginLeft: "10px" }}>({getLabel(18019, "必填")})</span>}
                        <span style={{ marginLeft: "15px" }}>{isBeagent && agent}</span>
                        {this.getRemarkDom(isInForm)}
                    </div> */}
                    {
                       <WfSignInput
                            ref={"forwardRemarkCK"}
                            markInfo={markInfo}
                            from_editsign = {true}
                            requestType={requestType}
                            requestid={requestid}
                            isShowSignInput={true}
                            editorId={'forwardremark'}
                            loadReady={this.onSingInputLoadReady.bind(this)}
                            onChange={onChangeEvent}
                            {...remarkInfo_new}
                            isEditorFocus={isEditorFocus}
                            controlVariableMap={controlVariableMap}
                            changeRemarkInfo={this.changeRemarkInfo.bind(this)}
                            saveCallBack={loadMarkInfo}
                            is_hide_botton = {true}
                            />
                    }
                </div>
            )
        } else {
            return (<div />);
        }
    }

    onChangeEvent(remark){
        const { commonParam} = allStore.globalStore;

       const WeaTools= getEcCom();
        window.newRemark=remark;
        logidMap[window.lsxlogid]=remark
        WeaTools.callApi("/api/workflow/AddSign4wfAction/updateRemark", 'POST', {mouldtext:remark,logid:window.lsxlogid,
            userid:commonParam.f_weaver_belongto_userid,username:commonParam.lastname}).then((d)=>{
                setTimeout(() => {
                    this.remarkCallBack(d);
                }, 301);
        });
    }

    //点击签字意见，打开签字意见编辑器
    initRemark() {
        const { batchControlVariableMap } = allStore.globalStore;
        batchControlVariableMap({ 'isShowSignInput': true, 'isEditorFocus': true });
    }


    changeRemarkInfo(params = {}) {
        const { changeSubmitParam } = allStore.globalStore;
        changeSubmitParam(params);
    }

    onSingInputLoadReady() {
        
    }


    remarkCallBack=(params)=>{
        setTimeout(() => {
            if (params.needDel) {
                jQuery("#log_del_"+params.logid).remove();
            }else{
                if (window.newRemark) {
                     let logObj =  jQuery("#log_" + params.logid);
                    logObj.html(window.newRemark);
                    let divObj = logObj.find("div").eq(0);
                    if(divObj.length==1){
                        divObj.css("display","inline");
                    }
                    this.delSomeHtml(logObj);
                    //window.newRemark = "";
                }
                let needAddOperator = params.needAddOperator;
                 if (needAddOperator != '') {
                    let index = params.index;
                    let obj;
                    if (index - 1 == 0) {//在母体追加
                        obj = jQuery("#log_operator_" + params.logid);
                    } else {//否则追加在最后面
                        obj = jQuery("#log_operator_" + params.logid + "_" + (index - 1));
                    }
                    obj.after("<span id='log_operator_" + params.logid + "_" + params.index + "'>" + needAddOperator + "</span>");
                }
            }
        })
    }
    
      delSomeHtml=(logObj)=>{
        let pObj = logObj.find("p:last");
        if(pObj.length == 1){
            let pHtml = pObj.html();
            //(new RegExp("word","gm"),"Excel")
            // pHtml=pHtml.replaceAll('<br>','');
            pHtml=pHtml.replace(new RegExp("<br>","gm"),"");
            pHtml=pHtml.replace(new RegExp("<br/>","gm"),"");
            // pHtml=pHtml.replaceAll('&nbsp;','');
            pHtml=pHtml.replace(new RegExp("&nbsp;","gm"),"");
            if (pHtml.length==0){
                pObj.remove();
                let pObj2 = logObj.find("p:last");
                if (pObj2.length==1){
                    pObj2.css("display","inline");
                }
            }else pObj.css("display","inline");
        }
    }
}